package com.liangzi.service_core.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liangzi.liangzi_common.exception.Assert;
import com.liangzi.liangzi_common.result.ResponseEnum;
import com.liangzi.liangzi_common.util.ArgumentEnum;
import com.liangzi.service_core.mapper.VisitUserMapper;
import com.liangzi.service_core.mapper.VisitUserWeixinOpenMapper;
import com.liangzi.service_core.pojo.bo.SnowflakeManager;
import com.liangzi.service_core.pojo.entity.VisitUser;
import com.liangzi.service_core.pojo.entity.VisitUserWeixinOpen;
import com.liangzi.service_core.pojo.vo.UserInfoVO;
import com.liangzi.service_core.service.VisitUserService;
import com.liangzi.servicebase.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * <p>
 * 小程序用户表 服务实现类
 * </p>
 *
 * @author zhj
 * @since 2021-12-13
 */
@Service
@Slf4j
public class VisitUserServiceImpl extends ServiceImpl<VisitUserMapper, VisitUser> implements VisitUserService {
    @Autowired
    private SnowflakeManager snowflakeManager;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private VisitUserWeixinOpenMapper visitUserWeixinOpenMapper;

    @Autowired
    private VisitUserMapper visitUserMapper;

    // 微信小程序授权登录功能
    public String queryOrSaveOpenId(String openId,
                                    String sessionKey,
                                    UserInfoVO userInfoVO) {
        String rd_session = UUID.randomUUID().toString();
        // 判断该用户的openid是否已经注册到我们的平台
        QueryWrapper<VisitUserWeixinOpen> wrapper = new QueryWrapper<>();
        wrapper.eq("open_id", openId);
        VisitUserWeixinOpen userWeixinOpenServiceOne = visitUserWeixinOpenMapper.selectOne(wrapper);
        if (userWeixinOpenServiceOne != null) { // 有且唯一
            String userId = userWeixinOpenServiceOne.getUserId();
            VisitUser user = visitUserMapper.selectById(userId);
            user.setUserName(userInfoVO.getName());
            user.setUserGender(userInfoVO.getSex());
            user.setUserVaatarUrl(userInfoVO.getAvatarUrl());
            user.setUserCity(userInfoVO.getCity());
            user.setUserCountry(userInfoVO.getCountry());
            int isUpdate = visitUserMapper.updateById(user);
            // 存储一下sessionkey
            QueryWrapper<VisitUserWeixinOpen> visitUserWeixinOpenQueryWrapper = new QueryWrapper<>();
            visitUserWeixinOpenQueryWrapper.eq("user_id", user.getUserId());
            VisitUserWeixinOpen one = visitUserWeixinOpenMapper.selectOne(visitUserWeixinOpenQueryWrapper);
            Assert.notNull(one, ResponseEnum.LOGIN_MOBILE_ERROR);
            one.setSessionKey(sessionKey);
            int b = visitUserWeixinOpenMapper.updateById(one);
            if (isUpdate > 0 && b > 0) {
                log.info("session:" + rd_session, userId, Long.parseLong(ArgumentEnum.SESSION_EXPIRE_TIME.getValue()));

                Object userJson = JSON.toJSON(user);
                redisUtil.set("session:" + rd_session, userId, Long.parseLong(ArgumentEnum.SESSION_EXPIRE_TIME.getValue()));
                redisUtil.set(userId, userJson, Long.parseLong(ArgumentEnum.SESSION_EXPIRE_TIME.getValue()));
                log.info("缓存存入成功-------------------------------");

                return rd_session;
            }
            return null;
        }
        // 没有 则 存入数据库
        VisitUserWeixinOpen userWeixinOpen = new VisitUserWeixinOpen();
        Long snowflakeID = null;
        try {
            snowflakeID = snowflakeManager.nextValue();
        } catch (Exception e) {
            e.printStackTrace();
        }
        userWeixinOpen.setOpenId(openId);
        Assert.notNull(snowflakeID, ResponseEnum.SNOW_FAKE_ID_ERROR);
        userWeixinOpen.setSessionKey(sessionKey);
        userWeixinOpen.setUserId(snowflakeID.toString());
        int isSave = visitUserWeixinOpenMapper.insert(userWeixinOpen);
        // 查询OpenId 与 用户与做关联
        if (isSave > 0) {
            // 创建用户
            VisitUser user = new VisitUser();
            user.setUserId(snowflakeID.toString());
            user.setUserName(userInfoVO.getName());
            user.setUserGender(userInfoVO.getSex());
            user.setUserVaatarUrl(userInfoVO.getAvatarUrl());
            user.setUserCity(userInfoVO.getCity());
            user.setUserCountry(userInfoVO.getCountry());
            int save = visitUserMapper.insert(user);
            if (save > 0) {
                log.info("session:" + rd_session, snowflakeID.toString(), Long.parseLong(ArgumentEnum.SESSION_EXPIRE_TIME.getValue()));
                String userJson = JSON.toJSONString(user);
                redisUtil.set("session:" + rd_session, snowflakeID.toString(), Long.parseLong(ArgumentEnum.SESSION_EXPIRE_TIME.getValue()));
                redisUtil.set(snowflakeID.toString(), userJson, Long.parseLong(ArgumentEnum.SESSION_EXPIRE_TIME.getValue()));
                return rd_session;
            }

        }
        return "";
    }
}
